package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {

    @Resource
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDTO) {
        dishService.saveWithFlavor(dishDTO);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
//    @GetMapping("/page")
//    public R<Page<DishDTO>> page(int page, int pageSize, String name) {
//        Page<DishDTO> pageInfo = new Page<>(page, pageSize);
//
//        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like(StringUtils.isNotBlank(name), "d.name", name);
//        queryWrapper.orderByDesc("d.update_time");
//        pageInfo = dishService.pageCustom(pageInfo, queryWrapper);
//
////        dishService.page(pageInfo, queryWrapper);
//        return R.success(pageInfo);
//    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDTO>> page(int page, int pageSize, String name) {

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.orderByDesc("update_time");
        dishService.page(pageInfo, queryWrapper);


        Page<DishDTO> dishDTOPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(pageInfo, dishDTOPage);

        // 设置records
        List<DishDTO> dishDTOList = new ArrayList<>();
        List<Dish> records = pageInfo.getRecords();
        records.forEach(record -> {
            DishDTO distDTO = new DishDTO();

            BeanUtils.copyProperties(record, distDTO);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            distDTO.setCategoryName(category.getName());

            dishDTOList.add(distDTO);
        });
        dishDTOPage.setRecords(dishDTOList);

        return R.success(dishDTOPage);
    }

    @GetMapping("/{id}")
    public R<DishDTO> get(@PathVariable Long id){
        DishDTO dishDTO = dishService.getByIdWithFlavor(id);
        return R.success(dishDTO);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO) {
        dishService.updateWithFlavor(dishDTO);
        return R.success("新增菜品成功");
    }

    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish) {
        List<DishDTO> dishDTOList = null;

        // 动态拼接key
        String redisKey = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDTOList = (List<DishDTO>) redisTemplate.opsForValue().get(redisKey);

        if(!CollectionUtils.isEmpty(dishDTOList)) {
            return R.success(dishDTOList);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(dish.getCategoryId()), Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(!ObjectUtils.isEmpty(dish.getStatus()), Dish::getStatus, dish.getStatus());
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(wrapper);

        dishDTOList = dishList.stream().map(item -> {
            DishDTO dishDTO = new DishDTO();

            BeanUtils.copyProperties(item, dishDTO);

            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(item.getId() != null, DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDTO.setFlavors(dishFlavorList);

            return dishDTO;
        }
        ).collect(Collectors.toList());

        redisTemplate.opsForValue().set(redisKey, dishDTOList);

        return R.success(dishDTOList);
    }


}
